


import 'dart:convert';
import 'dart:math';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_hotwork/HomePage.dart';
import 'package:flutter_hotwork/IPConfigAct.dart';
import 'package:flutter_hotwork/Myapplication.dart';
import 'package:flutter_hotwork/Toast.dart';
import 'package:flutter_hotwork/bean/BaseBean.dart';
import 'package:flutter_hotwork/bean/loginbean.dart';
import 'package:flutter_hotwork/home/Home.dart';
import 'package:flutter_hotwork/utils/AesUtil.dart';
import 'package:flutter_hotwork/utils/DioUtils.dart';
import 'package:flutter_hotwork/zhifa/QuestionUpList.dart';
import 'package:hb_check_code/hb_check_code.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'LoadingDialog.dart';
import 'package:encrypt/encrypt.dart';

class MyHomePage extends StatefulWidget {


  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
//手机号的控制器
  TextEditingController phoneController = TextEditingController();
  //用户类型的控制器
  TextEditingController userController = TextEditingController();
//密码的控制器
  TextEditingController passController = TextEditingController();

  TextEditingController codeController = TextEditingController();
  bool firstloaduser = true;
  var dropdownValue ;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    firstloaduser = true;
  }


  void getHttp(var name,var password) async {
    showDialog(
        context: context,
        builder: (context) {
          return new LoadingDialog();
        });
    var reqeuest =Map<Object,Object>();
    reqeuest["username"] = name;
    reqeuest["password"] = AESUtil.generateAESencry(password);
    try {
      Response response;
      response = await DioUtils.dio.post(DioUtils.API_PREFIX+"/sys/login", data: json.encode(reqeuest));

      Map respMap = json.decode(response.data);
      basebean base = basebean.fromJson(respMap);
      Navigator.pop(context);
        if (base.code == 200) {
        MyApplication.loginuserinfo = loginbean.fromJson(base.result);
        setUserName(name);
        setpassword(password);
        DioUtils.token = MyApplication.loginuserinfo.token;
        DioUtils.clear();
        DioUtils.createInstance();
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return new HomePage();
        }));
      }

      else {
        //  LocalToast.toast(context,msg: base.message);
        LocalToast.toast(context,msg:base.message);
      }
      print('响应数据：' + response.toString());
    } catch (e) {
      Navigator.pop(context);
      //  LocalToast.toast(context,msg: "网络错误");
      print('请求出错：' + e.toString());
    }
  }

  LocationFlutterPlugin _locationPlugin = new LocationFlutterPlugin();
  String code = "";

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;

    _locationPlugin.requestPermission();
    if(firstloaduser){
      code = "";
      for (var i = 0; i < 4; i++) {
        code = code + Random().nextInt(9).toString();
      }
      getUserName();
      getPassword();
    }

    return Scaffold(
      resizeToAvoidBottomPadding: false,


      body:
      Container(
        padding: EdgeInsets.only(left: 5, right: 5, top:100, bottom: 5),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/loginbgblue.jpg"),
            fit: BoxFit.fill,
          ),
        ),
        child:
        Column(
          children: <Widget>[
            Text("智慧热网管控系统",style: new TextStyle(color: Colors.white,
                fontSize: 24.0,
                fontWeight: FontWeight.w800),),
            Container(
              height: 800*rpx,
              padding:  EdgeInsets.only(left: 20, right: 20, top:80, bottom: 0),
              margin: const EdgeInsets.all(50),
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage("images/loginwhitebg.png"),
                  fit: BoxFit.fill,
                ),
              ),
              child:
              Column(
                children: <Widget>[
                  Container(
                    height: 30,
                    padding:  EdgeInsets.only(left: 10, right: 0, top:0, bottom: 0),
                    decoration: BoxDecoration(
                      border: new Border.all(color: Color(0xFF9E9E9E), width: 0.5), // 边色与边宽度
                      color: Colors.white, // 底色
                      //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                      borderRadius: BorderRadius.all(Radius.circular(15)),
                    ),
                    child:
                    TextField(
                      style: TextStyle(color: Colors.grey),
                      // controller: phoneController..text="admin",
                      controller: phoneController,
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(0),
                        icon: Image(height:20,width: 20,image: AssetImage('images/zhanghao.png')),
                        hintText: '请输入您的用户名',

                        hintStyle: TextStyle(color: Colors.grey),
//                            helperText: '请输入注册的手机号',
                        border:OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.transparent,
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.transparent,
                          ),
                        ),
                        disabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.transparent,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(
                            color: Colors.transparent,
                          ),
                        ),
                      ),
                      autofocus: false,
                    ),

                  ),
                  Container(
                      height: 30,
                      margin: EdgeInsets.only(left: 0, right: 0, top:20, bottom: 20),
                      padding:  EdgeInsets.only(left: 10, right: 0, top:0, bottom: 0),
                      decoration: BoxDecoration(
                        border: new Border.all(color: Color(0xFF9E9E9E), width: 0.5), // 边色与边宽度
                        color: Colors.white, // 底色
                        //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                        borderRadius: BorderRadius.all(Radius.circular(15)),
                      ),
                      child:
                      TextField(
                        style: TextStyle(color: Colors.grey),
                        // controller: passController..text="Jjrd2020!@#",
                        controller: passController,
                        keyboardType: TextInputType.visiblePassword,
                        obscureText:true,

                        decoration: InputDecoration(

                          contentPadding: EdgeInsets.all(0),
                          icon: Image(height:20,width: 20,image: AssetImage('images/mima.png')),
                          hintText: '请输入您的密码',
                          hintStyle: TextStyle(color: Colors.grey),
                          border:OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.transparent,
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.transparent,
                            ),
                          ),
                          disabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.transparent,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.transparent,
                            ),
                          ),
                        ),
                        autofocus: false,
                      )

                  ),
                  Row(children: [
                    Container(
                      height: 30,
                      width: 100,
                      padding:  EdgeInsets.only(left: 10, right: 0, top:0, bottom: 0),
                      decoration: BoxDecoration(
                        border: new Border.all(color: Color(0xFF9E9E9E), width: 0.5), // 边色与边宽度
                        color: Colors.white, // 底色
                        //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                        borderRadius: BorderRadius.all(Radius.circular(15)),
                      ),
                      child:
                      TextField(
                        style: TextStyle(color: Colors.grey),
                        // controller: phoneController..text="admin",
                        controller: codeController,
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(0),
                          hintText: '验证码',

                          hintStyle: TextStyle(color: Colors.grey),
                          border:OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.transparent,
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.transparent,
                            ),
                          ),
                          disabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.transparent,
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.transparent,
                            ),
                          ),
                        ),
                        autofocus: false,
                      ),
                    ),
                    Container(width: 10,),
                    InkWell(
                    onTap: (){
                      code = "";
                      for (var i = 0; i < 4; i++) {
                        code = code + Random().nextInt(9).toString();
                      }
                      setState(() {

                      });
                    }
                      ,
                      child:
                      HBCheckCode(
                      code: "$code",
                    ),
                    ),

                  ],),

                  //




                  ButtonTheme(
                    minWidth: 200.0,//设置最小宽度
                    height: 30.0,
                    child: RaisedButton(
                      onPressed: _login,
                      child: Text('登录',style: new TextStyle(color: Colors.white),
                      ),
                      color:Colors.blue,
                      shape:RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(15)),
                      ),
                    ),
                  ),

                  // InkWell(
                  //   onTap:(){
                  //   Navigator.push(context, MaterialPageRoute(builder: (context) {
                  //                 return new IPConfigPage();
                  //               }));
                  //   },
                  //   child:
                  //   Text("设置服务器地址",style: new TextStyle(color: Colors.blue,fontSize: 12),),
                  //
                  // ),


                ],
              ),
            ),

          ],),

      ),

    );


  }

  void _login() {
    if (codeController.text!=code) {
      showDialog(
          context: context,
          builder: (context) =>
              AlertDialog(
                title: Text('请填写正确的验证码'),
              ));
    }else{
      getHttp(phoneController.text,passController.text);
    }
    // else if (passController.text.length == 0) {
    //   showDialog(
    //       context: context,
    //       builder: (context) =>
    //           AlertDialog(
    //             title: Text('请填写密码'),
    //           ));
    // } else {



//  }
//     Navigator.push(context, MaterialPageRoute(builder: (context) {
//       return new HomePage();
//     }));

//    showDialog(
//        context: context,
//        builder: (context) =>
//            AlertDialog(
//              title: Text('登录成功'),
//            )
//    );

//    }
  }

  void onTextClear() {
    setState(() {
      phoneController.clear();
      passController.clear();
    });
  }
  setUserName(String username) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("username",username);
  }

  getUserName() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    phoneController..text = prefs.getString("username");
  }
  setpassword(String password) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    print(AESUtil.generateAESencry(password));
    prefs.setString("password",AESUtil.generateAESencry(password));
  }

  getPassword() async{
    firstloaduser = false;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    print(AESUtil.generateAESdecry(prefs.getString("password")));
    passController..text =AESUtil.generateAESdecry(prefs.getString("password"));
  }
}